<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { fetchAddDictData, fetchUpdateDictData } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';
import { yesOrNoOptions } from '@/constants/common';

defineOptions({
  name: 'ConfigOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** 字典类型 */
  dictType: string;
  /** the edit row data */
  rowData?: Api.System.DictType | null;
}
// 定义属性
const props = defineProps<Props>();
// 定义事件
interface Emits {
  (e: 'submitted'): void;
}
const emit = defineEmits<Emits>();

// 是否可见
const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '添加字典配置',
    edit: '编辑字典配置'
  };
  return titles[props.operateType];
});

// 模型
type Model = Pick<Api.System.DictData, 'dictType' | 'dictLabel' | 'dictValue' | 'status'>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    dictLabel: '',
    dictType: props.dictType,
    dictValue: '',
    status: '0'
  };
}

// 表单规则
type RuleKey = Extract<keyof Model, 'dictLabel' | 'dictValue' | 'dictType' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  dictLabel: defaultRequiredRule,
  dictValue: defaultRequiredRule,
  dictType: defaultRequiredRule,
  status: defaultRequiredRule
};

function handleInitModel() {
  // 不知道是否有更好的方法
  Object.assign(model, createDefaultModel(), {
    id: null,
    createBy: '',
    createTime: null,
    updateBy: null,
    updateTime: null
  });

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  // request
  let success: boolean = false;
  if (props.operateType === 'add') {
    const { error } = await fetchAddDictData(model);
    if (!error) success = true;
  } else if (props.operateType === 'edit') {
    const { error } = await fetchUpdateDictData(model);
    if (!error) success = true;
  }
  if (success) {
    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="字典标签" path="dictLabel">
          <NInput v-model:value="model.dictLabel" placeholder="请输入字典标签" />
        </NFormItem>
        <NFormItem label="字典类型" path="dictValue">
          <NInput v-model:value="model.dictValue" placeholder="请输入字典键值" />
        </NFormItem>
        <NFormItem label="状态" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
